﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Microsoft.VisualBasic;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.HtmlControls;


public class ServerValidate
{
    #region 验证函数部分代码

    /// <summary>
    /// 判断给定的字符串(strNumber)是否是数值型
    /// </summary>
    /// <param name="strNumber">要确认的字符串</param>
    /// <returns>是则返加true 不是则返回 false</returns>
    public static bool IsNumber(string strNumber)
    {
        return new Regex(@"^([-]|[1-9])[0-9]*$").IsMatch(strNumber);


        /*
        Regex objNotNumberPattern=new Regex("[^0-9.-]");
        Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
        Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
        string strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
        string strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
        Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");
        return !objNotNumberPattern.IsMatch(strNumber) &&
            !objTwoDotPattern.IsMatch(strNumber) &&
            !objTwoMinusPattern.IsMatch(strNumber) &&
            objNumberPattern.IsMatch(strNumber);
        */
    }

    /// <summary>
    /// 判断给定的字符串(strNumber)是否是由数字组成 如01922
    /// </summary>
    /// <param name="strNumber">要确认的字符串</param>
    /// <returns>是则返加true 不是则返回 false</returns>
    public static bool IsNumberString(string strNumber)
    {
        return new Regex(@"^[0-9]+$").IsMatch(strNumber);
        //return new Regex(@"^[0-9]{8}").IsMatch(strNumber);//8个数字组成
    }

    /// <summary>
    /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型
    /// </summary>
    /// <param name="strNumber">要确认的字符串数组</param>
    /// <returns>是则返加true 不是则返回 false</returns>
    public bool IsNumberArray(string[] strNumber)
    {
        if (strNumber == null)
        {
            return false;
        }
        if (strNumber.Length < 1)
        {
            return false;
        }
        foreach (string id in strNumber)
        {
            if (!IsNumber(id))
            {
                return false;
            }
        }
        return true;

    }

    /// <summary>
    /// 判断文件名是否为浏览器可以直接显示的图片文件名
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>是否可以直接显示</returns>
    public bool IsImgFilename(string filename)
    {
        filename = filename.Trim();
        if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
        {
            return false;
        }
        string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
        return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
    }

    /// <summary>
    /// 检测是否符合email格式
    /// </summary>
    /// <param name="strEmail">要判断的email字符串</param>
    /// <returns>判断结果</returns>
    public static bool IsValidEmail(string strEmail)
    {
        return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }

    /// <summary>
    /// 判断是否为base64字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public bool IsBase64String(string str)
    {
        //A-Z, a-z, 0-9, +, /, =
        return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
    }

    /// <summary>
    /// 检测是否有Sql危险字符
    /// </summary>
    /// <param name="str">要判断字符串</param>
    /// <returns>判断结果</returns>
    public bool IsSafeSqlString(string str)
    {

        return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
    }

    /// <summary>
    /// 检测是否有危险的可能用于链接的字符串
    /// </summary>
    /// <param name="str">要判断字符串</param>
    /// <returns>判断结果</returns>
    public bool IsSafeUserInfoString(string str)
    {
        return !Regex.IsMatch(str, @"/^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|$guestexp/is");
    }

    /// <summary>
    /// 是否为时间格式字符串
    /// </summary>
    /// <returns></returns>
    public static bool IsTimeString(string timeval)
    {
        return Regex.IsMatch(timeval, @"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
    }

    /// <summary>
    /// 验证字符串是否为日期时间格式.如2000-10-01 12:30:30
    /// </summary>
    /// <param name="datetime">日期时间字符串</param>
    /// <returns></returns>
    public static bool IsDateTimeString(string datetime)
    {
        //return Regex.IsMatch(datetime,@"(((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9]))|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29))|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)))((\s+(0?[1-9]|1[012])(:[0-5]\d){0,2}(\s[AP]M))?$|(\s+([01]\d|2[0-3])(:[0-5]\d){0,2})?$))");
        return Regex.IsMatch(datetime, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$");
    }

    /// <summary>
    /// 比较datetime1是否比datetime2大.
    /// </summary>
    /// <param name="datestart">datetime1</param>
    /// <param name="dateend">datetime2</param>
    /// <returns></returns>
    public static bool IsLargerDate(string datetime1, string datetime2)
    {

        DateTime dt1 = DateTime.Parse(datetime1);
        DateTime dt2 = DateTime.Parse(datetime2);

        int ts = DateTime.Compare(dt1, dt2);
        if (ts > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 判断文件流是否为UTF8字符集
    /// </summary>
    /// <param name="sbInputStream">文件流</param>
    /// <returns>判断结果</returns>
    private bool IsUTF8(FileStream sbInputStream)
    {
        int i;
        byte cOctets;  // octets to go in this UTF-8 encoded character 
        byte chr;
        bool bAllAscii = true;
        long iLen = sbInputStream.Length;

        cOctets = 0;
        for (i = 0; i < iLen; i++)
        {
            chr = (byte)sbInputStream.ReadByte();

            if ((chr & 0x80) != 0) bAllAscii = false;

            if (cOctets == 0)
            {
                if (chr >= 0x80)
                {
                    do
                    {
                        chr <<= 1;
                        cOctets++;
                    }
                    while ((chr & 0x80) != 0);

                    cOctets--;
                    if (cOctets == 0) return false;
                }
            }
            else
            {
                if ((chr & 0xC0) != 0x80)
                {
                    return false;
                }
                cOctets--;
            }
        }

        if (cOctets > 0)
        {
            return false;
        }

        if (bAllAscii)
        {
            return false;
        }

        return true;

    }

    /// <summary>
    /// 是否为ip
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public bool IsIP(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    /// <summary>
    /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
    /// </summary>
    /// <param name="ip"></param>
    /// <param name="iparray"></param>
    /// <returns></returns>
    public bool InIPArray(string ip, string[] iparray)
    {

        string[] userip = SplitString(ip, @".");
        for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
        {
            string[] tmpip = SplitString(iparray[ipIndex], @".");
            int r = 0;
            for (int i = 0; i < tmpip.Length; i++)
            {
                if (tmpip[i] == "*")
                {
                    return true;
                }

                if (userip.Length > i)
                {
                    if (tmpip[i] == userip[i])
                    {
                        r++;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }

            }
            if (r == 4)
            {
                return true;
            }


        }
        return false;

    }

    /// <summary>
    /// 判断字符串是否是yyyy-mm-dd字符串
    /// </summary>
    /// <param name="str">待判断字符串</param>
    /// <returns>判断结果</returns>
    public static bool IsDateString(string str)
    {
        //return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
        return Regex.IsMatch(str, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
    }


    #endregion

    /// <summary>
    /// 返回字符串真实长度, 1个汉字长度为2
    /// </summary>
    /// <returns></returns>
    public int GetStringLength(string str)
    {
        return Encoding.Default.GetBytes(str).Length;
    }

    /// <summary>
    /// 获得当前绝对路径
    /// </summary>
    /// <param name="strPath">指定的路径</param>
    /// <returns>绝对路径</returns>
    public string GetMapPath(string strPath)
    {
        if (HttpContext.Current != null)
        {
            return HttpContext.Current.Server.MapPath(strPath);
        }
        else //非web程序引用
        {
            return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
        }
    }

    /// <summary>
    /// 返回文件是否存在
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>是否存在</returns>
    public bool FileExists(string filename)
    {
        return System.IO.File.Exists(filename);
    }

    /// <summary>
    /// 以指定的ContentType输出指定文件文件
    /// </summary>
    /// <param name="filepath">文件路径</param>
    /// <param name="filename">输出的文件名</param>
    /// <param name="filetype">将文件输出时设置的ContentType</param>
    public void ResponseFile(string filepath, string filename, string filetype)
    {
        Stream iStream = null;

        // 缓冲区为10k
        byte[] buffer = new Byte[10000];

        // 文件长度
        int length;

        // 需要读的数据长度
        long dataToRead;

        try
        {
            // 打开文件
            iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);


            // 需要读的数据长度
            dataToRead = iStream.Length;

            HttpContext.Current.Response.ContentType = filetype;
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + UrlEncode(filename.Trim()).Replace("+", " "));

            while (dataToRead > 0)
            {
                // 检查客户端是否还处于连接状态
                if (HttpContext.Current.Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10000);
                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                    HttpContext.Current.Response.Flush();
                    buffer = new Byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    // 如果不再连接则跳出死循环
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write("Error : " + ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                // 关闭文件
                iStream.Close();
            }
        }
        HttpContext.Current.Response.End();
    }

    /// <summary>
    /// MD5函数
    /// </summary>
    /// <param name="str">原始字符串</param>
    /// <returns>MD5结果</returns>
    public string MD5(string str)
    {
        byte[] b = Encoding.Default.GetBytes(str);
        b = new MD5CryptoServiceProvider().ComputeHash(b);
        string ret = "";
        for (int i = 0; i < b.Length; i++)
            ret += b[i].ToString("x").PadLeft(2, '0');
        return ret;
    }

    /// <summary>
    /// SHA256函数
    /// </summary>
    /// /// <param name="str">原始字符串</param>
    /// <returns>SHA256结果</returns>
    public string SHA256(string str)
    {
        byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
        SHA256Managed Sha256 = new SHA256Managed();
        byte[] Result = Sha256.ComputeHash(SHA256Data);
        return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
    }

    /// <summary>
    /// 自定义的替换字符串函数
    /// </summary>
    public string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
    {
        return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
    }

    /// <summary>
    /// 返回标准日期格式yyyy-MM-dd
    /// </summary>
    public static string GetDate()
    {
        return DateTime.Now.ToString("yyyy-MM-dd");
    }

    /// <summary>
    /// 返回标准时间格式HH:mm:ss
    /// </summary>
    public static string GetTime()
    {
        return DateTime.Now.ToString("HH:mm:ss");
    }

    /// <summary>
    /// 返回标准时间格式yyyy-MM-dd HH:mm:ss
    /// </summary>
    public static string GetDateTime()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 返回相对于当前时间的相对天数
    /// </summary>
    public string GetDateTime(int relativeday)
    {
        return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 返回标准时间格式yyyy-MM-dd HH:mm:ss:fffffff
    /// </summary>
    public string GetDateTimeF()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
    }

    /// <summary>
    /// 返回标准时间 
    /// </sumary>
    public static string GetStandardDateTime(string fDateTime, string formatStr)
    {
        DateTime s = Convert.ToDateTime(fDateTime);
        return s.ToString(formatStr);
    }

    /// <summary>
    /// 返回标准时间 yyyy-MM-dd HH:mm:ss
    /// </summary>
    /// <param name="fDateTime"></param>
    /// <returns></returns>
    public static string GetStandardDateTime(string fDateTime)
    {
        return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 返回当前时间字符串 yyyy-MM-dd HH:mm:ss
    /// </summary>
    /// <returns></returns>
    public static string GetCurrentDateTimeString()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }

    /// <summary>
    /// 返回当前日期字符串 yyyy-MM-dd
    /// </summary>
    /// <returns></returns>
    public static string GetCurrentDateString()
    {
        return DateTime.Now.ToString("yyyy-MM-dd");
    }

    /// <summary>
    /// 改正sql语句中的转义字符
    /// </summary>
    public string mashSQL(string str)
    {
        string str2;

        if (str == null)
        {
            str2 = "";
        }
        else
        {
            str = str.Replace("\'", "'");
            str2 = str;
        }
        return str2;
    }

    /// <summary>
    /// 替换sql语句中的有问题符号
    /// </summary>
    public string ChkSQL(string str)
    {
        string str2;

        if (str == null)
        {
            str2 = "";
        }
        else
        {
            str = str.Replace("'", "''");
            str2 = str;
        }
        return str2;
    }

    /// <summary>
    /// 转换为静态html
    /// </summary>
    public void TransHtml(string path, string outpath)
    {
        Page page = new Page();
        StringWriter writer = new StringWriter();
        page.Server.Execute(path, writer);
        FileStream fs;
        if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
        {
            File.Delete(page.Server.MapPath("") + "\\" + outpath);
            fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
        }
        else
        {
            fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
        }
        byte[] bt = Encoding.Default.GetBytes(writer.ToString());
        fs.Write(bt, 0, bt.Length);
        fs.Close();
    }

    /// <summary>
    /// 分割字符串
    /// </summary>
    public string[] SplitString(string strContent, string strSplit)
    {
        if (strContent.IndexOf(strSplit) < 0)
        {
            string[] tmp = { strContent };
            return tmp;
        }
        return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
    }

    /// <summary>
    /// 替换html字符
    /// </summary>
    public string EncodeHtml(string strHtml)
    {
        if (strHtml != "")
        {
            strHtml = strHtml.Replace(",", "&def");
            strHtml = strHtml.Replace("'", "&dot");
            strHtml = strHtml.Replace(";", "&dec");
            return strHtml;
        }
        return "";
    }

    public string ClearHtml(string strHtml)
    {
        if (strHtml != "")
        {
            Regex r = null;
            Match m = null;

            r = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
            for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
            {
                strHtml = strHtml.Replace(m.Groups[0].ToString(), "");
            }
        }
        return strHtml;
    }

    /// <summary>
    /// 进行指定的替换(脏字过滤)
    /// </summary>
    public string StrFilter(string str, string bantext)
    {
        string text1 = "";
        string text2 = "";
        string[] textArray1 = SplitString(bantext, "\r\n");
        for (int num1 = 0; num1 < textArray1.Length; num1++)
        {
            text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
            text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
            str = str.Replace(text1, text2);
        }
        return str;
    }

    /// <summary>
    /// 获得伪静态页码显示链接
    /// </summary>
    /// <param name="curPage">当前页数</param>
    /// <param name="countPage">总页数</param>
    /// <param name="url">超级链接地址</param>
    /// <param name="extendPage">周边页码显示个数上限</param>
    /// <returns>页码html</returns>
    public string GetPageNumbers(int curPage, int countPage, string url, string expname, int extendPage)
    {
        int startPage = 1;
        int endPage = 1;

        string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
        string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">&raquo;</a>&nbsp;";

        if (countPage < 1) countPage = 1;
        if (extendPage < 3) extendPage = 2;

        if (countPage > extendPage)
        {
            if (curPage - (extendPage / 2) > 0)
            {
                if (curPage + (extendPage / 2) < countPage)
                {
                    startPage = curPage - (extendPage / 2);
                    endPage = startPage + extendPage - 1;
                }
                else
                {
                    endPage = countPage;
                    startPage = endPage - extendPage + 1;
                    t2 = "";
                }
            }
            else
            {
                endPage = extendPage;
                t1 = "";
            }
        }
        else
        {
            startPage = 1;
            endPage = countPage;
            t1 = "";
            t2 = "";
        }

        StringBuilder s = new StringBuilder("");

        s.Append(t1);
        for (int i = startPage; i <= endPage; i++)
        {
            if (i == curPage)
            {
                s.Append("&nbsp;");
                s.Append(i);
                s.Append("&nbsp;");
            }
            else
            {
                s.Append("&nbsp;<a href=\"");
                s.Append(url);
                s.Append("-");
                s.Append(i);
                s.Append(expname);
                s.Append("\">");
                s.Append(i);
                s.Append("</a>&nbsp;");
            }
        }
        s.Append(t2);

        return s.ToString();
    }

    /// <summary>
    /// 获得帖子的伪静态页码显示链接
    /// </summary>
    /// <param name="expname"></param>
    /// <param name="countPage">总页数</param>
    /// <param name="url">超级链接地址</param>
    /// <param name="extendPage">周边页码显示个数上限</param>
    /// <returns>页码html</returns>
    public string GetPostPageNumbers(int countPage, string url, string expname, int extendPage)
    {
        int startPage = 1;
        int endPage = 1;
        int curPage = 1;

        string t1 = "<a href=\"" + url + "-1" + expname + "\">&laquo;</a>&nbsp;";
        string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">&raquo;</a>&nbsp;";

        if (countPage < 1) countPage = 1;
        if (extendPage < 3) extendPage = 2;

        if (countPage > extendPage)
        {
            if (curPage - (extendPage / 2) > 0)
            {
                if (curPage + (extendPage / 2) < countPage)
                {
                    startPage = curPage - (extendPage / 2);
                    endPage = startPage + extendPage - 1;
                }
                else
                {
                    endPage = countPage;
                    startPage = endPage - extendPage + 1;
                    t2 = "";
                }
            }
            else
            {
                endPage = extendPage;
                t1 = "";
            }
        }
        else
        {
            startPage = 1;
            endPage = countPage;
            t1 = "";
            t2 = "";
        }

        StringBuilder s = new StringBuilder("");

        s.Append(t1);
        for (int i = startPage; i <= endPage; i++)
        {
            s.Append("&nbsp;<a href=\"");
            s.Append(url);
            s.Append("-");
            s.Append(i);
            s.Append(expname);
            s.Append("\">");
            s.Append(i);
            s.Append("</a>&nbsp;");
        }
        s.Append(t2);

        return s.ToString();
    }

    /// <summary>
    /// 获得页码显示链接
    /// </summary>
    /// <param name="curPage">当前页数</param>
    /// <param name="countPage">总页数</param>
    /// <param name="url">超级链接地址</param>
    /// <param name="extendPage">周边页码显示个数上限</param>
    /// <returns>页码html</returns>
    public string GetPageNumbers(int curPage, int countPage, string url, int extendPage)
    {
        int startPage = 1;
        int endPage = 1;

        if (url.IndexOf("?") > 0)
        {
            url = url + "&";
        }
        else
        {
            url = url + "?";
        }

        string t1 = "<a href=\"" + url + "&page=1" + "\">&laquo;</a>&nbsp;";
        string t2 = "<a href=\"" + url + "&page=" + countPage + "\">&raquo;</a>&nbsp;";

        if (countPage < 1) countPage = 1;
        if (extendPage < 3) extendPage = 2;

        if (countPage > extendPage)
        {
            if (curPage - (extendPage / 2) > 0)
            {
                if (curPage + (extendPage / 2) < countPage)
                {
                    startPage = curPage - (extendPage / 2);
                    endPage = startPage + extendPage - 1;
                }
                else
                {
                    endPage = countPage;
                    startPage = endPage - extendPage + 1;
                    t2 = "";
                }
            }
            else
            {
                endPage = extendPage;
                t1 = "";
            }
        }
        else
        {
            startPage = 1;
            endPage = countPage;
            t1 = "";
            t2 = "";
        }

        StringBuilder s = new StringBuilder("");

        s.Append(t1);
        for (int i = startPage; i <= endPage; i++)
        {
            if (i == curPage)
            {
                s.Append("&nbsp;");
                s.Append(i);
                s.Append("&nbsp;");
            }
            else
            {
                s.Append("&nbsp;<a href=\"");
                s.Append(url);
                s.Append("page=");
                s.Append(i);
                s.Append("\">");
                s.Append(i);
                s.Append("</a>&nbsp;");
            }
        }
        s.Append(t2);

        return s.ToString();
    }

    /// <summary>
    /// 返回 HTML 字符串的编码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>编码结果</returns>
    public static string HtmlEncode(string str)
    {
        return HttpUtility.HtmlEncode(str);
    }

    /// <summary>
    /// 返回 HTML 字符串的解码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>解码结果</returns>
    public static string HtmlDecode(string str)
    {
        return HttpUtility.HtmlDecode(str);
    }

    /// <summary>
    /// 返回 URL 字符串的编码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>编码结果</returns>
    public string UrlEncode(string str)
    {
        return HttpUtility.UrlEncode(str);
    }

    /// <summary>
    /// 返回 URL 字符串的编码结果
    /// </summary>
    /// <param name="str">字符串</param>
    /// <returns>解码结果</returns>
    public string UrlDecode(string str)
    {
        return HttpUtility.UrlDecode(str);
    }

    /// <summary>
    /// 返回指定目录下的非 UTF8 字符集文件
    /// </summary>
    /// <param name="Path">路径</param>
    /// <returns>文件名的字符串数组</returns>
    public string[] FindNoUTF8File(string Path)
    {
        StringBuilder filelist = new StringBuilder();
        DirectoryInfo Folder = new DirectoryInfo(Path);

        FileInfo[] subFiles = Folder.GetFiles();
        for (int j = 0; j < subFiles.Length; j++)
        {
            if (subFiles[j].Extension.ToLower().Equals(".htm"))
            {
                FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
                bool bUtf8 = IsUTF8(fs);
                fs.Close();
                if (!bUtf8)
                {
                    filelist.Append(subFiles[j].FullName);
                    filelist.Append("\r\n");
                }
            }
        }
        return SplitString(filelist.ToString(), "\r\n");

    }

    /// <summary>
    /// 格式化字节数字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public string FormatBytesStr(int bytes)
    {
        if (bytes > 1073741824)
        {
            return ((double)(bytes / 1073741824)).ToString("0") + "G";
        }
        if (bytes > 1048576)
        {
            return ((double)(bytes / 1048576)).ToString("0") + "M";
        }
        if (bytes > 1024)
        {
            return ((double)(bytes / 1024)).ToString("0") + "K";
        }
        return bytes.ToString() + "Bytes";
    }

    /// <summary>
    /// 将long型数值转换为Int32类型
    /// </summary>
    /// <param name="objNum"></param>
    /// <returns></returns>
    public int SafeInt32(object objNum)
    {
        if (objNum == null)
        {
            return 0;
        }
        string strNum = objNum.ToString();
        if (IsNumber(strNum))
        {

            if (strNum.ToString().Length > 9)
            {
                return int.MaxValue;
            }
            return Int32.Parse(strNum);
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    /// 返回相差的秒数
    /// </summary>
    /// <param name="Time"></param>
    /// <param name="Sec"></param>
    /// <returns></returns>
    public int StrDateDiffSeconds(string Time, int Sec)
    {
        TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
        if (ts.TotalSeconds > int.MaxValue)
        {
            return int.MaxValue;
        }
        else if (ts.TotalSeconds < int.MinValue)
        {
            return int.MinValue;
        }
        return (int)ts.TotalSeconds;
    }

    /// <summary>
    /// 返回相差的分钟数
    /// </summary>
    /// <param name="time"></param>
    /// <param name="minutes"></param>
    /// <returns></returns>
    public int StrDateDiffMinutes(string time, int minutes)
    {
        if (time == "" || time == null)
            return 1;
        TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
        if (ts.TotalMinutes > int.MaxValue)
        {
            return int.MaxValue;
        }
        else if (ts.TotalMinutes < int.MinValue)
        {
            return int.MinValue;
        }
        return (int)ts.TotalMinutes;
    }

    /// <summary>
    /// 返回相差的小时数
    /// </summary>
    /// <param name="time"></param>
    /// <param name="hours"></param>
    /// <returns></returns>
    public int StrDateDiffHours(string time, int hours)
    {
        if (time == "" || time == null)
            return 1;
        TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
        if (ts.TotalHours > int.MaxValue)
        {
            return int.MaxValue;
        }
        else if (ts.TotalHours < int.MinValue)
        {
            return int.MinValue;
        }
        return (int)ts.TotalHours;
    }

    /// <summary>
    /// 为脚本替换特殊字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string ReplaceStrToScript(string str)
    {
        str = str.Replace("\\", "\\\\");
        str = str.Replace("'", "\\'");
        str = str.Replace("\"", "\\\"");
        return str;
    }

    /// <summary>
    /// 获得Assembly版本号
    /// </summary>
    /// <returns></returns>
    public static string GetAssemblyVersion()
    {
        Assembly myAssembly = Assembly.GetExecutingAssembly();
        FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
        return string.Format("{0}.{1}.{2}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart);
    }

    /// <summary>
    /// 获得Assembly产品名称
    /// </summary>
    /// <returns></returns>
    public string GetAssemblyProductName()
    {
        Assembly myAssembly = Assembly.GetExecutingAssembly();
        FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
        return myFileVersion.ProductName;
    }

    /// <summary>
    /// 获得Assembly产品版权
    /// </summary>
    /// <returns></returns>
    public string GetAssemblyCopyright()
    {
        Assembly myAssembly = Assembly.GetExecutingAssembly();
        FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
        return myFileVersion.LegalCopyright;
    }

    public static string GetWeekDay(string datetime)
    {
        try
        {
            DateTime dt = DateTime.Parse(datetime);

            string Temp = "";
            switch (dt.DayOfWeek)
            {
                case DayOfWeek.Sunday:
                    Temp = "星期天";
                    break;
                case DayOfWeek.Monday:
                    Temp = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    Temp = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    Temp = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    Temp = "星期四";
                    break;
                case DayOfWeek.Friday:
                    Temp = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    Temp = "星期六";
                    break;
            }
            return Temp;
        }
        catch
        {
            return "";
        }
    }

    public static string GetWeekDay()
    {
        return GetWeekDay(DateTime.Now.ToString());
    }

    public static string GetChineseDate()
    {
        return DateTime.Now.ToString("yyyy年MM月dd日");
    }

}

